package com.yituo.mjworld.mvc.action.user;

import com.yituo.mjworld.core.annotation.Check;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.action.IBaseAction;
import com.yituo.mjworld.mvc.entity.web.UserRole;
import com.yituo.mjworld.mvc.entity.web.WebUser;
import com.yituo.mjworld.mvc.entity.web.WebUserCollect;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import com.yituo.mjworld.mvc.service.impl.CollectServiceImpl;
import com.yituo.mjworld.mvc.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@Component
public class CollectAction implements IBaseAction {
  @Autowired
  CollectServiceImpl collectService;
  @Autowired
  ProductServiceImpl productService;

  /**
   * 获取全部的收藏夹内容
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Check(form = QueryForm.class)
  @Override
  public void getList(MyHttpRequest req, MyHttpResponse res) throws IOException {
    QueryForm form = (QueryForm) req.getForm();
    WebUser user = req.getCurrentUser();
    form.getParam().clear();
    if (UserRole.isWebUser(user)) {
      form.getParam().put("userId", user.getId());
    }
    if (UserRole.isSuperAdmin(user) || UserRole.isWebUser(user)) {
      res.success(collectService.getList(form));
      return;
    }
    res.failed("暂未开放权限!");
  }

  /**
   * 删除收藏夹的记录
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Check(form = DeleteForm.class)
  public void delete(MyHttpRequest req, MyHttpResponse res) throws IOException {
    DeleteForm form = (DeleteForm) req.getForm();
    WebUser user = req.getCurrentUser();
    if (UserRole.isWebUser(user) || UserRole.isAgent(user)) {
      // 代理和普通用户只能删除自己的收藏记录
      form.getParam().put("userId", user.getId());
    }
    if (UserRole.isAdminOrAgentOrNormalUser(user)) {
      res.setResult(collectService.delete(form));
      return;
    }
    res.failed("暂未开放权限!");
  }

  /**
   * 保存或者更新
   *
   * @param req
   * @param res
   * @throws IOException
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   */
  @Override
  @Check(form = WebUserCollect.class)
  public void saveOrUpdate(MyHttpRequest req, MyHttpResponse res) throws IOException, InvocationTargetException, IllegalAccessException {
    WebUserCollect collect = (WebUserCollect) req.getForm();
    if (!productService.productIsExits(collect.getProductId())) {
      res.failed("产品不存在!");
      return;
    }
    collect.setUserId(req.getCurrentUser().getId());
    res.setResult(collectService.saveOrUpdate(collect));
  }
}
